package com.spring.cootask.web.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.spera.shopoa.util.ShopOaSessionUtil;
import com.spring.common.web.service.CommonService;
import com.spring.cootask.web.model.*;
import com.spring.cootask.web.service.*;
import com.spring.security.core.annotation.OaUserPermission;
import com.spring.security.core.util.ApplicationUtils;
import com.spring.security.core.validators.Insert;
import com.spring.security.web.model.BaseResult;
import com.spring.tools.Result;
import com.spring.tools.ValidatorResultHandler;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by WoJunyu on 2016/9/20.
 */
@Controller
@RequestMapping(value = "/fetask")
public class FeTaskController {

    @Resource
    private FeTaskService feTaskService;

    @Resource
    private CommonService commonService;

    @Resource
    private TaskTransService taskTransService;

    @Resource
    private CooTaskService cooTaskService;

    @Resource
    private FeModuleService feModuleService;

    @Resource
    private FeBackgroundService feBackgroundService;

    /**
     * 发起人主页
     * @return
     */
    @OaUserPermission(value = "/fetask/create")
    @RequestMapping(value = "/create")
    public ModelAndView create(Model model,HttpServletRequest request){
        ShopOaSessionUtil.OaUser oaUser = ShopOaSessionUtil.getOaUser(request);
        model.addAttribute("deptId",oaUser.getUser_shopdept_id());
        return new ModelAndView("main/fetask/task/create");
    }

    /**
     * 接收人主页
     * @return
     */
    @OaUserPermission(value = "/fetask/trans")
    @RequestMapping(value = "/trans")
    public ModelAndView trans(Model model,HttpServletRequest request){
        ShopOaSessionUtil.OaUser oaUser = ShopOaSessionUtil.getOaUser(request);
        model.addAttribute("deptId",oaUser.getUser_shopdept_id());
        model.addAttribute("user",oaUser);
        return new ModelAndView("main/fetask/task/trans");
    }

    /**
     * 流转任务创建人页面（与trans的区别是下发时部门树显示的是全公司的）
     * @return
     */
    @OaUserPermission(value = "/fetask/transTop")
    @RequestMapping(value = "/transTop")
    public ModelAndView transTop(Model model,HttpServletRequest request){
        ShopOaSessionUtil.OaUser oaUser = ShopOaSessionUtil.getOaUser(request);
        model.addAttribute("deptId",oaUser.getUser_shopdept_id());
        model.addAttribute("user",oaUser);
        return new ModelAndView("main/fetask/task/trans_top");
    }

    /**
     * 表单类录入信息主页
     *
     * @return
     */
    @RequestMapping(value = "/userValue")
    public ModelAndView userValue(Model model, @RequestParam String feTaskUserid,
                                  HttpServletRequest request) {
//        ShopOaSessionUtil.OaUser oaUser = ShopOaSessionUtil.getOaUser(request);
        //获取自定义结构
        List<FeTaskUserTable> retL=taskTransService.feTaskUserTable(feTaskUserid,"0");
        //fTaskUserid = "21ee4fab-097c-4398-9899-bd66f6148fc1";
        //根据用户获取数据
        FeTaskUserWithBLOBs retV=taskTransService.feTaskUser(feTaskUserid);
        cleanData(retV,retL);
/*        String planDataJson=retV.getPlanDataJson();*/
/*        model.addAttribute("planDataJson", planDataJson);*/
        model.addAttribute("dataList", retL);
        model.addAttribute("taskUserId", feTaskUserid);
        return new ModelAndView("main/fetask/task/uservalue");
    }

    /**
     * 表单类录入信息主页
     *
     * @return
     */
    @RequestMapping(value = "/userValueShow")
    public ModelAndView userValueShow(Model model, @RequestParam String feTaskUserid,
                                  HttpServletRequest request) {
//        ShopOaSessionUtil.OaUser oaUser = ShopOaSessionUtil.getOaUser(request);
        //获取自定义结构
        List<FeTaskUserTable> retL=taskTransService.feTaskUserTable(feTaskUserid,"0");
        //fTaskUserid = "21ee4fab-097c-4398-9899-bd66f6148fc1";
        //根据用户获取数据
        FeTaskUserWithBLOBs retV=taskTransService.feTaskUser(feTaskUserid);
        cleanData(retV,retL);
/*        String planDataJson=retV.getPlanDataJson();*/
/*        model.addAttribute("planDataJson", planDataJson);*/
        model.addAttribute("dataList", retL);
        model.addAttribute("taskUserId", feTaskUserid);
        return new ModelAndView("main/fetask/task/uservalue_show");
    }

    private void  cleanData(FeTaskUserWithBLOBs retV,List<FeTaskUserTable> retL){
        if (retV != null && ApplicationUtils.isNotNull(retV)) {
            //json数据反序列化
            List<Map<String, Object>> retJson = JSON.parseObject(retV.getPlanDataJson(), new TypeReference<List<Map<String,Object>>>(){});
            Map<String, Object> retm = null;
            if(retJson!=null&&retJson.size()>0){
                retm = retJson.get(0);
            }
//            JSON.parseObj
            //组合自定义字段和对应的值
            if(retm!=null){
                for (FeTaskUserTable one : retL) {
                    for (Map.Entry<String, Object> entry : retm.entrySet()) {
                        //System.out.println("Key = " + entry.getKey() + ", Value = " + entry.getValue());
                        if (entry.getKey().equals(one.getColumnCode())) {
                            one.setValue(ApplicationUtils.Object2String(entry.getValue()));
                        }
                    }
                }
            }
        }
    }

    /**
     * 发起人列表数据（任务发起界面数据）
     * @return
     */
    @RequestMapping(value = "/queryTask")
    @ResponseBody
    public Object queryTask(String page,String rows,FeTask data,HttpServletRequest request) {
        Map<String, Object> retD = new HashMap<String, Object>();
        ShopOaSessionUtil.OaUser oaUser = ShopOaSessionUtil.getOaUser(request);
        //用户未登录
        if(oaUser!=null&&!ApplicationUtils.isNotNull(oaUser.getOa_user_id())){
            return null;
        }
        data.setInitialoperatorid(oaUser.getOa_user_id());
        try{
            PageHelper.startPage(Integer.parseInt(page), Integer.parseInt(rows));
            List<FeTask> list = feTaskService.selectTaskByParm(data);
            PageInfo pageObj = new PageInfo(list);
            retD.put("total", pageObj.getTotal());
            retD.put("rows", list);
        }catch(Exception e){
            e.printStackTrace();
        }
        return retD;
    }

    /**
     *接收人人列表数据（流转界面数据）
     * @return
     */
    @RequestMapping(value = "/queryTaskTrans")
    @ResponseBody
    public Object queryTaskTrans(String page,String rows,FeTask data,HttpServletRequest request) {
        Map<String, Object> retD = new HashMap<String, Object>();
        ShopOaSessionUtil.OaUser oaUser = ShopOaSessionUtil.getOaUser(request);
        //用户未登录
        if(oaUser!=null&&!ApplicationUtils.isNotNull(oaUser.getOa_user_id())){
            return null;
        }
        data.setUserId(oaUser.getOa_user_id());
        try{
            PageHelper.startPage(Integer.parseInt(page), Integer.parseInt(rows));
            List<FeTask> list = feTaskService.selectTaskTransByParm(data);
            PageInfo pageObj = new PageInfo(list);
            retD.put("total", pageObj.getTotal());
            retD.put("rows", list);
        }catch(Exception e){
            e.printStackTrace();
        }
        return retD;
    }

    /**
     * 下拉父级任务
     * @param data
     * @param request
     * @return
     */
    @RequestMapping(value = "/selectTask")
         @ResponseBody
         public Object selectTask(FeTask data,HttpServletRequest request) {
        ShopOaSessionUtil.OaUser oaUser = ShopOaSessionUtil.getOaUser(request);
        //用户未登录
        if(oaUser!=null&&!ApplicationUtils.isNotNull(oaUser.getOa_user_id())){
            return null;
        }
        data.setUserId(oaUser.getOa_user_id());
        List<FeTask> list = null;
        try{
            list = feTaskService.selectTaskTransByParm(data);           
        }catch(Exception e){
            e.printStackTrace();
        }
        return list;
    }

    @RequestMapping(value = "/selectTableDetail")
    @ResponseBody
    public Object selectTableDetail(String tableId,HttpServletRequest request) {
        List<TaskTablebaseDetail> list = null;
        try{
            list = feTaskService.selectTableDetail(tableId);
        }catch(Exception e){
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 修改或新增
     * @return
     */
    //@OaRestPermission(value="/cootask/saveTask")
    //@OaUserPermission(value="/cootask/saveTask")
    @RequestMapping(value = "/saveTask")
    @ResponseBody
    public Object saveTask(@RequestBody @Validated({Insert.class}) FeTask data,BindingResult result,HttpServletRequest request) {
        Result retVal = ValidatorResultHandler.handle(result);
        if("0".equalsIgnoreCase(retVal.getStatus())){
            return retVal;
        }
        BaseResult ret = null;
        try {
            ShopOaSessionUtil.OaUser oaUser = ShopOaSessionUtil.getOaUser(request);
            ret = feTaskService.saveTask(data, oaUser);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }

    /**
     * 删除
     * @return
     */
    @RequestMapping(value = "/deleteTask")
    @ResponseBody
    public Object deleteTask(String id) {
        BaseResult ret = null;
        try {
            ret = feTaskService.deleteTask(id);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ret;
    }
    
    
    @RequestMapping(value = "/commitTask")
    @ResponseBody
    public Object commitTask(String taskUserID) {
        BaseResult ret = null;
        try {
            ret = feTaskService.commitPop(taskUserID);
        } catch (Exception e) {
        	ret = new BaseResult("0","系统异常");
            e.printStackTrace();
        }
        return ret;
    }

    @RequestMapping(value = "/fullpage")
    public ModelAndView fullpage(@RequestParam  String taskId,
                                 Model model,HttpServletRequest request){
        List<Map<String,Object>> retDataList = new ArrayList();

        Map<String,Object> parm = new HashMap();
        parm.put("task_id",taskId);
        //背景图
        FeBackground retBack = feBackgroundService.selectByParm(parm);
        if(retBack!=null){
            model.addAttribute("background",retBack.getBackUrl());
        }

        List<FeTaskUserWithBLOBs> list = taskTransService.transDetail(taskId);
        for(FeTaskUserWithBLOBs one:list){
            List<FeTaskUserTable> retL=taskTransService.feTaskUserTable(one.getId(),"0");
            cleanData(one,retL);
            Map<String,Object> mone = new HashMap();
            mone.put("userName",one.getUserName());
            mone.put("userDataList",retL);
            retDataList.add(mone);
        }

        //标题页及目录页
        List<FeModule> mList = feModuleService.selectByParm(parm);
        model.addAttribute("mList",mList);

        model.addAttribute("dataList",retDataList);
        return new ModelAndView("main/fetask/task/fullpageshow");
    }

    @RequestMapping(value = "/fullpagegrid")
    public ModelAndView fullpagegrid(@RequestParam  String taskId,
                                 Model model,HttpServletRequest request){
        List<Map<String,Object>> retDataList = new ArrayList();

        Map<String,Object> parm = new HashMap();
        parm.put("task_id",taskId);
//        //背景图
//        FeBackground retBack = feBackgroundService.selectByParm(parm);
//        if(retBack!=null){
//            model.addAttribute("background",retBack.getBackUrl());
//        }

        List<FeTaskUserWithBLOBs> list = taskTransService.transDetail(taskId);
        for(FeTaskUserWithBLOBs one:list){
            //获取字段column
            List<FeTaskUserTable> dataInfo = taskTransService.feTaskUserTable(one.getId(),"");
            if(dataInfo!=null&&dataInfo.size()>0){
                String data= JSONObject.toJSONString(dataInfo);
                //获取字段对应的用户数据
                FeTaskUserWithBLOBs feTaskUser=taskTransService.feTaskUser(one.getId());
                Map<String,Object> mone = new HashMap();
                mone.put("userName",one.getUserName());
                mone.put("userGridColumn",data);
                mone.put("userGridData",feTaskUser.getUserDataJson());
                retDataList.add(mone);
            }
        }
        //标题页及目录页
        List<FeModule> mList = feModuleService.selectByParm(parm);
        model.addAttribute("mList",mList);

        model.addAttribute("dataList",retDataList);
        return new ModelAndView("main/fetask/task/fullpagegridshow");
    }
    
    @RequestMapping(value = "/febackground", method = RequestMethod.GET)
    @ResponseBody
    public Object febackground(HttpServletRequest request) {
        List<FeBackground> list = null;
        try{
            list = feBackgroundService.select();
        }catch(Exception e){
            e.printStackTrace();
        }
        return list;
    }

    @RequestMapping(value = "/femodule", method = RequestMethod.GET)
    @ResponseBody
    public Object femodule(String type,HttpServletRequest request) {
        List<FeModule> list = null;
        try{
            list = feModuleService.select(type);
        }catch(Exception e){
            e.printStackTrace();
        }
        return list;
    }
}
